package com.cash.channel.web.controller;

import com.alibaba.fastjson.JSON;
import com.cash.channel.web.annotation.RestControllerMapper;
import com.cash.channel.api.exception.CashChannelException;
import com.cash.channel.api.model.channel.RequireParam;
import com.cash.channel.api.service.ChannelService;
import com.cash.channel.api.util.ValidatorUtil;
import com.cash.channel.web.model.RequestModel;
import com.cash.channel.api.util.ApiUtils;
import com.cash.common.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

/**
 *
 */
@Slf4j
@RestControllerMapper("/apply")
public class ApplyController extends BaseController {

    @Autowired
    private ChannelService channelService;

    @PostMapping("/submit")
    public Result submit(@RequestBody RequestModel requestModel) {
        try {
            return doDispatch("applySubmit", requestModel, dataMap -> {
                ApiUtils.checkParamsExist(dataMap, "name","idNo","mobile","orderNo","userId");
                if (!ValidatorUtil.checkIdNo(MapUtils.getString(dataMap, "idNo"))) {
                    throw new CashChannelException("身份证["+ org.apache.commons.collections4.MapUtils.getString(dataMap, "idNo")+"]格式错误");
                }
                if (!ValidatorUtil.isMobile(MapUtils.getString(dataMap, "mobile"))) {
                    throw new CashChannelException("手机号["+ org.apache.commons.collections4.MapUtils.getString(dataMap, "mobile")+"]格式错误");
                }
                RequireParam requireParams = channelService.findApplySubmitRequireParam(requestModel.getChannel());
                for (RequireParam requireParam: requireParams.getParentSubParam()) {
                    if (requireParam.isRoot()) {
                        ApiUtils.checkParamsExist(dataMap, requireParam.subKeys().toArray(new String[]{}));
                    }
                    ApiUtils.checkParamsExist(MapUtils.getMap(dataMap, requireParam.getParamName()), requireParam.subKeys().toArray(new String[]{}));
                }
            });
        } catch (CashChannelException e) {
            log.error(e.getErrMessage(), e);
            return Result.failed(e.getErrMessage());
        }
    }

    @PostMapping("/audit/status")
    public Result auditStatus(@RequestBody RequestModel requestModel) {
        try {
            return doDispatch("applyAuditStatus", requestModel, dataMap -> {
                ApiUtils.checkParamsExist(dataMap, "orderNo");});
        } catch (CashChannelException e) {
            log.error(e.getErrMessage(), e);
            return Result.failed(e.getErrMessage());
        }
    }

}
